<?php

class Default_Model_TongCongNo extends Henry_Db_Table
{
	static private $TBNAME = "tongcongno";
	protected $_name = 'tongcongno'; 
  	protected $_primary = 'customer_id';
  	public function init()
  	{
  		$this->_name = parent::PREFIX.$this->_name;
  	}
	public function capnhapCongNo($cusID,$SoTien)
	{
		//Kiem tra xem cong no cua khach hang da co chua.
		//Neu chua co thi minh them moi. 
		//Neu co roi minh se cong don So Tien vao.
		if ($this->tontaiCongNo($cusID))
		{
			$SoTienCu = $this->layTongTien($cusID);
			$data = array(
				'tongtien'    => ($SoTien + $SoTienCu)
			);
			$where = $this->_db->quoteInto("customer_id = ?",$cusID);
			$this->update($data,$where);
		}
		else 
		{
			$data = array(
				'customer_id' => $cusID,
				'tongtien'    => $SoTien
			);
			$this->insert($data);
		}
	}
	public function suaTongSoTien($cusID,$tongSoTien)
	{
		$data = array(
			'tongtien'    => $tongSoTien
		);
		$where = $this->_db->quoteInto("customer_id = ?",$cusID);
		$this->update($data,$where);
	}
	public function tontaiCongNo($cusID)
	{
		$select = $this->_db->select();
		$select->from($this->_name,array('customer_id'))
		       ->where('customer_id = ?',$cusID);
		$data = $this->_db->fetchAll($select);
		if (empty($data)) return false;
		return true;
	}
	public function layTongTien($cusID)
	{
		$select = $this->_db->select();
		$select->from($this->_name,array('tongtien'))
		       ->where('customer_id = ?',$cusID);
		$data = $this->_db->fetchOne($select);
		return $data;
	}
	public static function getTBName()
	{
		return parent::PREFIX.self::$TBNAME; 
	}
	public function xoaTongCongNo($id)
	{
		$where = $this->_db->quoteInto("customer_id = ?",$id);
		return $this->delete($where);	
	}
}

?>